#/usr/bin/env python
# -*- coding: UTF-8 -*-

'''
Copyright (C) 2010 dbzhang800@gmail.com
All rights reserved.

''' 

import sys
import os
import platform
import shutil
import subprocess
import re

class MyData(object):
    def __init__(self):
        self.wd = None
        self.elenspos = None
        self.aperturessize = None
        self.landenergy = None
        self.ai = None
        self.beamspot = None
        self.sphericalaber = None
        self.chromaticaber = None
        self.excitation = None
        self.sensitivities = None


#outputfile = file(os.path.join(os.path.dirname(self.inputfilename), "result.cache"),  "w")

def readData(filename):
    inputfile = file(filename)
    linecount = -1
    for i in range(8):
        line = inputfile.readline()
        if line:
            if line.startswith("wdlist"):
                wdlist = line.split()[1:]
            elif line.startswith("elensposlist"):
                elensposlist = line.split()[1:]
            elif line.startswith("aperturesizelist"):
                aperturesizelist = line.split()[1:]
            elif line.startswith("landenergylist"):
                landenergylist = line.split()[1:]
            linecount += 1
        else:
            break
    if linecount !=  7:
        print (u"数据文件错误，停止提取")
        return None
    else:
        print ('wdlist ' + ' '.join(wdlist))
        print ('elensposlist ' + ' '.join(elensposlist))
        print ('aperturesizelist '+ ' '.join(aperturesizelist))
        print ('landenergylist ' + ' '.join(landenergylist))
        allcount = len(wdlist) * len(elensposlist) * len(aperturesizelist) * len(landenergylist)
        print ("all {}".format(allcount))
       
    data = []
    for wd_index in range(len(wdlist)):
        data.append([])
        for elenspos_index in range(len(elensposlist)):
            data[wd_index].append([])
            for aperturessize_index in range(len(aperturesizelist)):
                data[wd_index][elenspos_index].append([])
                for landenergy_index in range(len(landenergylist)):
                    d = readDataLine(inputfile)
                    if d:
                        data[wd_index][elenspos_index][aperturessize_index].append(d)
                    else:
                        print (u"数据文件错误，停止提取")
                        return None
    return data

def dataToFloat(d):
    if not d:
        return None
    if d.strip() == 'None':
        return None
    return float(d)

def readDataLine(inputfile):
    line = inputfile.readline()
    if not line:
        self.logdata.emit(u"数据文件错误，停止提取")
        return None
    items=line.split(',')
    if len(items)!=10:
        self.logdata.emit(u"数据文件错误，停止提取")
        return None

    linedata = MyData()        
    linedata.wd = dataToFloat(items[0])
    linedata.elenspos = dataToFloat(items[1])
    linedata.aperturessize = dataToFloat(items[2])
    linedata.landenergy = dataToFloat(items[3])
    linedata.ai =  dataToFloat(items[4])
    linedata.beamspot =  dataToFloat(items[5])
    linedata.sphericalaber = dataToFloat(items[6])
    linedata.chromaticaber =  dataToFloat(items[7])
    linedata.excitation =  dataToFloat(items[8])
    linedata.sensitivities = dataToFloat(items[9])
    return linedata

if __name__ == '__main__':
    import copy
    data = readData("../result.txt")

    if not data:
        print 'error'
        
    wd_size= len(data)
    elenspos_size = len(data[0])
    aperturesize_size = len(data[0][0])
    le_size = len(data[0][0][0])
    #-------------------------------------------------------------
    outfile = file("output.txt", 'w')
    for wd_index in range(wd_size):
        for le_index in range(le_size):
            min_data = 10000
            min_d = None
            for elenspos_index in range(elenspos_size):
                for aperturesize_index in range(aperturesize_size):
                    d = data[wd_index][elenspos_index][aperturesize_index][le_index]
                    if d.beamspot and d.beamspot < min_data:
                        min_data = d.beamspot
                        min_d  = d
            if not min_d:
                continue
            print (min_d.wd, min_d.landenergy, min_d.beamspot, min_d.sphericalaber,
                   min_d.chromaticaber, min_d.ai, min_d.elenspos, min_d.aperturessize)
            if min_d.beamspot and min_d.sphericalaber and min_d.chromaticaber and min_d.ai:
                outfile.write("{:10.2f} {:10.2f} {:10.5f} {:10.2e} {:10.2e} {:10.3f} {:10.1f} {:10.2f} {:10.3f}\n".
                          format(min_d.wd, min_d.landenergy, min_d.beamspot, min_d.sphericalaber,
                                 min_d.chromaticaber, min_d.ai,min_d.excitation, min_d.elenspos, min_d.aperturessize))

    outfile.close()

    #-------------------------------------------------------------
    outfile = file("output.txt2", 'w')
    for wd_index in range(wd_size):
        for le_index in range(le_size):
            min_data = 10000
            min_d = None
            min_d_elenspos = None
            for elenspos_index in range(elenspos_size):
                for aperturesize_index in range(aperturesize_size):
                    d = data[wd_index][elenspos_index][aperturesize_index][le_index]
                    if d.beamspot and d.beamspot < min_data:
                        min_data = d.beamspot
                        min_d  = d
                        min_d_elenspos = data[wd_index][0][aperturesize_index][le_index]
            if not min_d:
                continue
            print (min_d_elenspos.wd, min_d_elenspos.landenergy, min_d_elenspos.beamspot, min_d_elenspos.sphericalaber,
                   min_d_elenspos.chromaticaber, min_d_elenspos.ai, min_d_elenspos.elenspos, min_d_elenspos.aperturessize)
            if min_d.beamspot and min_d.sphericalaber and min_d.chromaticaber and min_d.ai:
                outfile.write("{:10.2f} {:10.2f} {:10.5f} {:10.2e} {:10.2e} {:10.3f} {:10.1f} {:10.2f} {:10.3f}\n".
                          format(min_d_elenspos.wd, min_d_elenspos.landenergy, min_d_elenspos.beamspot, min_d_elenspos.sphericalaber,
                                 min_d_elenspos.chromaticaber, min_d_elenspos.ai,min_d_elenspos.excitation, min_d_elenspos.elenspos,
                                 min_d_elenspos.aperturessize))

    outfile.close()
    
    raw_input("Press any key...")
    
